package com.ncmmall.mall.controller.business.marketing;

import com.ncmmall.application.business.goods.GoodsApplication;
import com.ncmmall.application.securitys.logs.OperationLogApplication;
import com.ncmmall.domain.business.goods.Goods;
import com.ncmmall.domain.business.goods.QGoods;
import com.ncmmall.domain.business.goods.channel.GoodsChannel;
import com.ncmmall.domain.business.goods.channel.QGoodsChannel;
import com.ncmmall.domain.business.marketing.seckill.GroupBookingGoods;
import com.ncmmall.domain.business.order.groupbooking.GroupBooking;
import com.ncmmall.domain.business.order.groupbooking.GroupBookingOrder;
import com.ncmmall.domain.business.order.groupbooking.QGroupBooking;
import com.ncmmall.mall.controller.securitys.shiro.Securitys;
import com.ncmmall.mall.params.PageParams;
import com.ncmmall.querychannel.QueryPage;
import com.ncmmall.querychannel.QueryPageRequest;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 拼团商品管理审核
 *
 * @author linxs
 * @date 2020-02-03 14:35
 */
@Controller
@RequestMapping(value = "/mall/groupBooking")
@Slf4j
public class GroupBookingController {

    @Autowired
    private QueryChannelService queryChannelService;

    @Autowired
    private GoodsApplication goodsApplication;

    @Autowired
    private OperationLogApplication logApplication;

    /**
     * 拼团商品列表
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    private String list(Model model, PageParams pageParams, Goods goods) {

        QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageParams.getPageNo());
        Map<String, Object> params = Maps.newHashMap();

        QueryPage<Goods> page;
        if (goods.getGroupBookingStatus() == 6) {
            QueryPage<GroupBookingGoods> page2 = queryChannelService.findPage("select b from GroupBookingGoods b where b.groupBookingStatus = 6 order by b.createTime desc", pageRequest.setParams(params), GroupBookingGoods.class);
            List<Goods> goodsList = new ArrayList<>();
            for (GroupBookingGoods groupBookingGoods : page2.getResult()) {
                Goods g = groupBookingGoods.getGoods();
                g.setGroupBookingPrice(groupBookingGoods.getGroupBookingPrice());
                g.setGroupBookingStore(groupBookingGoods.getGroupBookingStore());
                g.setGroupBookingCondition(groupBookingGoods.getGroupBookingCondition());
                g.setGroupBookingTotal(groupBookingGoods.getGroupBookingTotal());
                g.setGroupBookingBeginTime(groupBookingGoods.getGroupBookingBeginTime());
                g.setGroupBookingEndTime(groupBookingGoods.getGroupBookingEndTime());
                g.setGroupBookingLimit(groupBookingGoods.getGroupBookingLimit());
                g.setSalesVolume(groupBookingGoods.getGroupBookingSalesVolume());
                g.setGroupBookingStatus(groupBookingGoods.getGroupBookingStatus());
                goodsList.add(g);
            }
            page = new QueryPage<>(page2.getTotalCount(), goodsList, page2.getPageNo(), page2.getPageSize());
        } else {
            String hql = builderSQL("select u from Goods u where u.marketingType = 4 ", params, goods);
            page = queryChannelService.findPage(hql, pageRequest.setParams(params), Goods.class);
        }

        model.addAttribute("page", page).addAttribute("params", goods).addAttribute("channels", queryChannelService.findAll(QGoodsChannel.goodsChannel.status.eq(2).and(QGoodsChannel.goodsChannel.level.eq(1)).and(QGoodsChannel.goodsChannel.deleteStatus.eq(0)), GoodsChannel.class));

        return "mall/marketing/groupBooking/list";
    }


    /**
     * 开团管理列表
     */
    @RequestMapping(value = "/open/list", method = RequestMethod.GET)
    private String openList(Model model, PageParams pageParams, GroupBooking groupBooking) {

        QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageParams.getPageNo());
        Map<String, Object> params = Maps.newHashMap();
        String hql = builderGroupBookSQL("select u from GroupBooking u where u.status > 0 ", params, groupBooking);
        QueryPage<GroupBooking> page = queryChannelService.findPage(hql, pageRequest.setParams(params), GroupBooking.class);

        model.addAttribute("page", page).addAttribute("params", groupBooking);

        return "mall/marketing/groupBooking/open/list";
    }

    /**
     * 参团管理
     */
    @RequestMapping(value = "/order/list", method = RequestMethod.GET)
    private String orderList(Model model, PageParams pageParams, GroupBookingOrder groupBooking) {

        QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageParams.getPageNo());
        Map<String, Object> params = Maps.newHashMap();
        String hql = builderGroupBookingOrderSQL("select u from GroupBookingOrder u where u.type = 2 ", params, groupBooking);
        QueryPage<GroupBookingOrder> page = queryChannelService.findPage(hql, pageRequest.setParams(params), GroupBookingOrder.class);

        model.addAttribute("page", page).addAttribute("params", groupBooking);

        return "mall/marketing/groupBooking/order/list";
    }

    private String builderGroupBookingOrderSQL(String sql, Map<String, Object> params, GroupBookingOrder groupBooking) {

        if (!Strings.isNullOrEmpty(groupBooking.getOrderNo())) {
            sql += " and u.orderNo = :no ";
            params.put("no", groupBooking.getOrderNo());
        }

        if (null != groupBooking.getSku() && null != groupBooking.getSku().getGoods() && !Strings.isNullOrEmpty(groupBooking.getSku().getGoods().getName())) {
            sql += " and u.sku.goods.name like :name ";
            params.put("name", "%" + groupBooking.getSku().getGoods().getName() + "%");
        }

        if (null != groupBooking.getGroupBooking() && null != groupBooking.getGroupBooking().getMember() && !Strings.isNullOrEmpty(groupBooking.getGroupBooking().getMember().getNickname())) {
            sql += " and u.groupBooking.member.nickname like :nickname ";
            params.put("nickname", "%" + groupBooking.getGroupBooking().getMember().getNickname() + "%");
        }

        if (null != groupBooking.getMember() && !Strings.isNullOrEmpty(groupBooking.getMember().getNickname())) {
            sql += " and u.member.nickname like :mnickname ";
            params.put("mnickname", "%" + groupBooking.getMember().getNickname() + "%");
        }

        if (null != groupBooking.getMember() && !Strings.isNullOrEmpty(groupBooking.getMember().getMobile())) {
            sql += " and u.member.mobile = :mobile ";
            params.put("mobile", groupBooking.getMember().getMobile());
        }

        return sql;
    }

    /**
     * 详情
     */
    @RequestMapping(value = "/open/{id}/detail", method = RequestMethod.GET)
    private String openDetail(Model model, @PathVariable("id") long id) {

        GroupBooking groupBooking = queryChannelService.findOne(QGroupBooking.groupBooking.id.eq(id), GroupBooking.class);

        model.addAttribute("groupBooking", groupBooking);

        return "mall/marketing/groupBooking/open/detail";

    }

    private String builderGroupBookSQL(String sql, Map<String, Object> params, GroupBooking goods) {

        if (!Strings.isNullOrEmpty(goods.getGroupBookingNo())) {
            sql += " and u.groupBookingNo = :no ";
            params.put("no", goods.getGroupBookingNo());
        }

        if (null != goods.getSku() && null != goods.getSku().getGoods() && !Strings.isNullOrEmpty(goods.getSku().getGoods().getName())) {
            sql += " and u.sku.goods.name like :name ";
            params.put("name", "%" + goods.getSku().getGoods().getName() + "%");
        }

        if (null != goods.getMerchant() && !Strings.isNullOrEmpty(goods.getMerchant().getShopName())) {
            sql += " and u.merchant.shopName like :shopname ";
            params.put("shopname", goods.getMerchant().getShopName());
        }

        if (null != goods.getMember() && !Strings.isNullOrEmpty(goods.getMember().getNickname())) {
            sql += " and u.member.nickname like :nickname ";
            params.put("nickname", goods.getMember().getNickname());
        }

        return sql;
    }

    /**
     * 详情
     */
    @RequestMapping(value = "/{id}/detail", method = RequestMethod.GET)
    private String detail(Model model, @PathVariable("id") long id) {

        Goods goods = queryChannelService.findOne(QGoods.goods.id.eq(id), Goods.class);

        model.addAttribute("goods", goods);

        return "mall/marketing/groupBooking/detail";

    }


    /**
     * 审核页面
     */
    @RequestMapping(value = "/{id}/process", method = RequestMethod.GET)
    private String process(Model model, @PathVariable("id") long id) {

        Goods goods = queryChannelService.findOne(QGoods.goods.id.eq(id), Goods.class);

        model.addAttribute("goods", goods).addAttribute("_method", "PUT");

        return "mall/marketing/groupBooking/check";
    }

    /**
     * 审核拼团活动
     */
    @RequestMapping(value = "/{id}/process", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> process(HttpServletRequest request, Goods params) {
        try {
            goodsApplication.groupBookingProcess(params);
            logApplication.eventOfSystem(Securitys.currentUser(), "审核拼团活动" + params.getName(), Securitys.getIp(request));
            return ImmutableMap.of("status", true);
        } catch (Exception e) {
            log.error("[审核特价活动异常]", e);
            return ImmutableMap.of("status", false);
        }
    }

    /**
     * 条件筛选
     */
    private String builderSQL(String sql, Map<String, Object> params, Goods goods) {

        if (null != goods.getGoodsChannel() && goods.getGoodsChannel().getId() > 0) {
            goods.setGoodsChannel(queryChannelService.findOne(QGoodsChannel.goodsChannel.id.eq(goods.getGoodsChannel().getId()), GoodsChannel.class));

            sql += " and u.goodsChannel.id = :cid ";
            params.put("cid", goods.getGoodsChannel().getId());

        } else if (null != goods.getGoodsChannel() && goods.getGoodsChannel().getParent().getId() > 0) {
            goods.getGoodsChannel().setParent(queryChannelService.findOne(QGoodsChannel.goodsChannel.id.eq(goods.getGoodsChannel().getParent().getId()), GoodsChannel.class));

            sql += " and u.goodsChannel.parent.id = :cid ";
            params.put("cid", goods.getGoodsChannel().getParent().getId());

        } else if (null != goods.getGoodsChannel() && goods.getGoodsChannel().getParent().getParent().getId() > 0) {
            goods.getGoodsChannel().getParent().setParent(queryChannelService.findOne(QGoodsChannel.goodsChannel.id.eq(goods.getGoodsChannel().getParent().getParent().getId()), GoodsChannel.class));

            sql += " and u.goodsChannel.parent.parent.id = :cid ";
            params.put("cid", goods.getGoodsChannel().getParent().getParent().getId());
        }

        if (goods.getRecommendInt() == 1) {
            sql += " and u.recommend = true ";
        }

        if (goods.getRecommendInt() == 2) {
            sql += " and u.recommend = false ";
        }

        if (goods.getGroupBookingStatus() > 0) {
            sql += " and u.groupBookingStatus = :status ";
            params.put("status", goods.getGroupBookingStatus());
        } else {
            sql += " and u.groupBookingStatus in (2,3,4,5,6) ";
        }

        if (!Strings.isNullOrEmpty(goods.getGoodsNo())) {
            sql += " and u.goodsNo like :goodsno ";
            params.put("goodsno", "%" + goods.getGoodsNo() + "%");
        }

        if (!Strings.isNullOrEmpty(goods.getName())) {
            sql += " and u.name like :name ";
            params.put("name", "%" + goods.getName() + "%");
        }

        if (!Strings.isNullOrEmpty(goods.getOrderByCreateTime())) {
            sql += " order by u.createTime " + goods.getOrderByCreateTime();
        }

        if (!Strings.isNullOrEmpty(goods.getOrderByCreateTime())) {
            sql += " order by u.createTime " + goods.getOrderByCreateTime();
        } else if (!Strings.isNullOrEmpty(goods.getOrderByPrice())) {
            sql += " order by u.groupBookingPrice " + goods.getOrderByPrice();
        } else if (!Strings.isNullOrEmpty(goods.getOrderByStore())) {
            sql += " order by u.groupBookingStore " + goods.getOrderByStore();
        } else if (!Strings.isNullOrEmpty(goods.getOrderBySalesVolume())) {
            sql += " order by u.salesVolume " + goods.getOrderBySalesVolume();
        } else {
            sql += " order by u.createTime desc ";
        }

        return sql;
    }


}
